package org.codefinger.dao;

import java.util.Map;

import org.codefinger.dao.impl.DataAccesser;
import org.codefinger.dao.impl.QueryParam;
import org.codefinger.dao.impl.SQLVisitor;
import org.codefinger.dao.impl.sql.UValue;
import org.codefinger.dao.impl.sql.Where;

public class UpdateWhere implements Updater {

	private DataAccesser	dataAccesser;

	private String			table;

	private UValue			uValue;

	private Where			where;

	public UpdateWhere(DataAccesser dataAccesser, String table, UValue uValue, String condition) {
		super();
		this.dataAccesser = dataAccesser;
		this.table = table;
		this.uValue = uValue;
		this.where = dataAccesser.createWhere(condition, uValue.getParamIndex());
	}

	@Override
	public int execute(Object... params) {
		QueryParam queryParam = new QueryParam(params);
		SQLVisitor sqlVisitor = new SQLVisitor(queryParam);
		sqlVisitor.appendSQL("UPDATE ");
		sqlVisitor.appendSQL(table);
		uValue.visit(sqlVisitor);
		where.visit(sqlVisitor);
		return dataAccesser.executeUpdate(sqlVisitor.getSQL(), sqlVisitor.getParams());
	}

	@Override
	public int execute(Map<String, Object> params) {
		QueryParam queryParam = new QueryParam(params);
		SQLVisitor sqlVisitor = new SQLVisitor(queryParam);
		sqlVisitor.appendSQL("UPDATE ");
		sqlVisitor.appendSQL(table);
		uValue.visit(sqlVisitor);
		where.visit(sqlVisitor);
		return dataAccesser.executeUpdate(sqlVisitor.getSQL(), sqlVisitor.getParams());
	}

	@Override
	public UpdaterChain putParam(String name, Object value) {
		final QueryParam queryParam = new QueryParam();
		queryParam.setNamedParam(name, value);
		return new UpdaterChain() {

			@Override
			public UpdaterChain putParam(String name, Object value) {
				queryParam.setNamedParam(name, value);
				return this;
			}

			@Override
			public int execute() {
				SQLVisitor sqlVisitor = new SQLVisitor(queryParam);
				sqlVisitor.appendSQL("UPDATE ");
				sqlVisitor.appendSQL(table);
				uValue.visit(sqlVisitor);
				where.visit(sqlVisitor);
				return dataAccesser.executeUpdate(sqlVisitor.getSQL(), sqlVisitor.getParams());
			}
		};
	}

}
